import datetime
import os

from other.cfg import Config
from other.change_format import change_format
from other.sql_montage import sqlMontage
from other.status import Status
from server.Mysql import MySQL


class overhaul_config:
    def __init__(self):
        self.cfg = Config()
        self.st = Status()
        self.db = MySQL(self.cfg.res['mysql']['database'], 'overhaul_config')
        self.cf = change_format()
        self.sm = sqlMontage()

    # 获取大修区域
    def get_overhaul_config(self, data):
        result = {'msg': '成功', 'code': 200, 'data': [], 'total': None}
        sqls = f"select oc.*,oi.`overhaul_code`,oi.`overhaul_name`,oi.`overhaul_addr` from `overhaul_config` oc join `overhaul_info` oi on oc.`overhaul_info_id`=oi.`overhaul_info_id` and oi.`del_flag`='{self.st.get_status('delFlag', '存在')}' and oi.`status`='{self.st.get_status('status', '启用')}' where oc.`del_flag`='{self.st.get_status('delFlag', '存在')}' "
        sql = ""
        pages = ''
        if data != {}:
            if data.get('pageNum') is not None and data.get('pageSize') is not None:
                if data['pageNum'] != '' and data['pageSize'] != '':
                    pages = " limit {},{}".format(int(data['pageNum']) * int(data['pageSize']) - int(data['pageSize']),
                                                  int(data['pageSize']))
            if data.get('overhaulConfigName') is not None:
                if data['overhaulConfigName'] != '':
                    sql = sql + " and oc.`overhaul_config_name` like '%{}%'".format(data['overhaulConfigName'])
            if data.get('status') is not None:
                if data['status'] != '':
                    sql = sql + " and oc.`status`='{}'".format(data['status'])
            if data.get('beginTime') is not None and data.get('endTime') is not None:
                if data['beginTime'] != '' and data['endTime'] != '':
                    sql = (sql + " and ('{}'<=oc.`create_time` and oc.`create_time`<='{}')".
                           format(data['beginTime'], data['endTime']))
        total = self.db.gets(sqls + sql)
        result['total'] = len(total)
        if sql != "":
            sql = sqls + sql + ' ORDER BY oc.`create_time` DESC ' + f'{pages}'
        else:
            sql = sqls + ' ORDER BY oc.`create_time` DESC ' + f'{pages}'
        res = self.db.gets(sql)
        if res != ():
            for r in res:
                for key, value in r.items():
                    if isinstance(value, datetime.datetime):
                        r[key] = value.strftime("%Y-%m-%d %H:%M:%S")
                result['data'].append(r)
        result = self.cf.changes_format(result)
        return result

    # 新增大修区域
    def overhaul_config_add(self, data, userInfo):
        result = {'msg': '成功', 'code': 200}
        times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        g_sql = f"where `overhaul_config_name`='{data['overhaulConfigName']}'"
        g_res = self.db.get(g_sql)
        if g_res != ():
            result['code'] = 500
            result['msg'] = '大修区域名称重复'
        else:
            data['create_by'] = userInfo['userName']
            data['create_time'] = times
            add_sql = self.sm.add_sql_data(data, 'overhaul_config')
            self.db.adds(add_sql, 'overhaul_config')
        return result

    # 修改大修区域
    def overhaul_config_edit(self, data, userInfo):
        result = {'msg': '成功', 'code': 200}
        times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        g_sql = f"where `overhaul_config_name`='{data['overhaulConfigName']}'"
        g_res = self.db.get(g_sql)
        ff = False
        filename = ''
        if g_res != ():
            for g in g_res:
                if g['overhaul_config_id'] == data['overhaulConfigId']:
                    ff = True
                    if g['pic'] is not None:
                        if g['pic'] != '':
                            if g['pic'] != data['pic']:
                                filename = g['pic']
                else:
                    if g['overhaul_config_name'] == data['overhaulConfigName']:
                        result['msg'] = '大修区域名称重复'
                    ff = False
                    result['code'] = 500
                    break
        else:
            ff = True
        if ff:
            if filename != '':
                ffname = 'data/overhaul_config/'+filename.split('/')[-1]
                if os.path.exists(ffname):
                    os.remove(ffname)
            if 'createTime' in data:
                del data['createTime']
            data['update_by'] = userInfo['userName']
            data['update_time'] = times
            edit_sql = self.sm.edit_sql_data(data, 'overhaul_config', 'overhaul_config_id', data['overhaulConfigId'])
            self.db.edits(edit_sql, 'overhaul_config')
        return result

    # 删除大修区域
    def overhaul_config_del(self, data, userInfo):
        result = {'msg': '成功', 'code': 200}
        times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        ids = [int(x) for x in data.split(',')]
        for i in ids:
            dd = {'del_flag': self.st.get_status('delFlag', '已删除'), 'update_by': userInfo['userName'],
                  'update_time': times}
            edit_sql = self.sm.edit_sql_data(dd, 'overhaul_config', 'overhaul_config_id', i)
            self.db.edits(edit_sql, 'overhaul_config')
            cd = {'overhaul_config_id': "None", 'update_by': userInfo['userName'],
                  'update_time': times}
            cd_edit_sql = self.sm.edit_sql_data(cd, 'camera_info', 'overhaul_config_id', i)
            self.db.edits(cd_edit_sql, 'camera_info')
        return result
